package com.group.insight.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

/**
 * Name: JwtUtil
 * Package: com.group.insight.util
 * Date: 2024/11/07 - 19:21
 * Description:
 *
 * @author Junhui Zhang
 * @version v1.0
 */

public class JwtUtil {
    /**
     * 令牌有效期
     */
    private static final long FUTURE = 7 * 24 * 60 * 60 * 1000;
    /**
     * 密钥
     */
    private static final SecretKey SECRET_KEY;

    static {
        SECRET_KEY = Jwts.SIG.HS256.key().build();
    }

    /**
     * 生成token
     * @param map 添加的具体信息
     * @return token字符串
     */
    public static String generateToken(Map<String, Object> map) {
        return Jwts.builder().signWith(SECRET_KEY).claims(map).issuedAt(new Date())
                       .expiration(generateExpirationDate()).compact();
    }

    /**
     * 解析token
     * @param token 生成的token
     * @return JWS
     */
    public static Jws<Claims> parseToken(String token) {
        try {
            return Jwts.parser().verifyWith(SECRET_KEY).build().parseSignedClaims(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + FUTURE);
    }

    /**
     * 校验token的合法性
     * @param token 生成的token
     * @return true | false
     */
    public static boolean validateToken(String token) {
        Jws<Claims> claimsJws = parseToken(token);
        return claimsJws != null && !isTokenExpired(token);
    }

    private static boolean isTokenExpired(String token) {
        Date expiredData = getExpiredData(token);
        return expiredData.before(new Date());
    }

    private static Date getExpiredData(String token) {
        Jws<Claims> claimsJws = parseToken(token);
        return claimsJws.getPayload().getExpiration();
    }
}
